package com.ambow.lhd.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpStatus;

import com.ambow.lhd.adapter.DemandListAdapter;
import com.ambow.lhd.api.Api;
import com.ambow.lhd.common.AppException;
import com.ambow.lhd.common.HttpHelper;
import com.ambow.lhd.common.HttpHelper.Callback;
import com.ambow.lhd.common.PageModel;
import com.ambow.lhd.entity.ItemList;
import com.ambow.lhd.entity.Users;
import com.ambow.lhd.service.MyApplication;
import com.ambow.lhd.util.PullDownView;
import com.ambow.lhd.util.PullDownView.UpdateHandler;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 求购信息列表
 * 
 * @author 林东
 *
 */
public class DemandListActivity extends Activity implements OnClickListener, UpdateHandler, OnItemClickListener{
	private MyApplication myApplication;
	private String string;
	private int pageNo = 1;
	private String condition = "category"; //条件是根据商品类型查询    // 查询条件是根据账户查询还是根据类型查询
	private List<ItemList> listDatas = new ArrayList<ItemList>(); 
	private LinearLayout footer; //listView的底部
	private ProgressBar listView_foot_progress; //listView 的底部进度条
	private TextView listView_foot_more; //显示“加载全部”
	private DemandListAdapter adapter; //适配器
	private boolean hasMore = false;
	private int lastItem;
	
	private ImageButton ib_back;//返回
	private TextView tv_update; 
	private TextView tv_type; //类型
	
	private ListView lv_list; //商品列表
	private PullDownView list_pdv; //下拉刷新功能视图类
	
	private Button btn_demand; //求购信息
	private Button btn_whole; //全部
	private Button btn_my_school; //本校
	
	private String school = ""; //根据学校查询全部信息
	private View dialogView;
	private Dialog dialog; //弹出对话框
	private Button btn_back; //取消登陆按钮
	private Button btn_determine; //确定登陆按钮 
//	private TextView tv_content;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.information_list);
		
		myApplication = (MyApplication) this.getApplicationContext();
		myApplication.addActivity(this);
		
		tv_type = (TextView) findViewById(R.id.type_title_tv_type);
		ib_back = (ImageButton) findViewById(R.id.type_title_ib_back);
		tv_update = (TextView) findViewById(R.id.type_title_tv_update);
		
		btn_whole = (Button) findViewById(R.id.information_list_btn_whole);
		btn_my_school = (Button) findViewById(R.id.information_list_btn_my_school);
		btn_demand = (Button) findViewById(R.id.information_list_btn_demand);
		//发布信息列表
		list_pdv = (PullDownView) this.findViewById(R.id.information_list_pdv);
		lv_list = (ListView) list_pdv.findViewById(R.id.information_list_lv_list);
		//确认对话框
		dialogView = getLayoutInflater().inflate(R.layout.alert_dialog, null, false);
//		tv_content = (TextView) dialogView.findViewById(R.id.alert_dialog_tv_content);
		//创建对话框
		dialog = new Dialog(this, R.style.myDialogTheme);
		//对话框事件    
		//注意  必须通过<dialogView.findViewById()>查找布局文件中的指定Id的组件,findViewById()找不到组件
		btn_back = (Button) dialogView.findViewById(R.id.alert_dialog_btn_back);
		btn_determine = (Button) dialogView.findViewById(R.id.alert_dialog_btn_determine);
		
		
		//注册监听事件
		ib_back.setOnClickListener(this);
		tv_update.setVisibility(View.GONE);
		btn_whole.setOnClickListener(this);
		btn_my_school.setOnClickListener(this);
		btn_demand.setOnClickListener(this);
		btn_demand.setText("发布信息");
		
		btn_back.setOnClickListener(this); 
		btn_determine.setOnClickListener(this);
		
		//把点击的类型显示在页面头部
		Intent intent = getIntent();
		string = intent.getStringExtra("type");
		tv_type.setText(string); 
		//初始化下拉刷新
		initPullDownView();
		//加载数据
		loadData(pageNo); 
		System.out.println("--------加载求购数据--------");
	}
	
	@Override
	public void onClick(View v) {
		//返回首页
		if(v == ib_back){
			Intent intent = new Intent(this, MainActivity.class);
			this.startActivity(intent);
			this.finish();
		}
		//发布信息
		if(v == btn_demand){
			System.out.println("--------v == btn_demand-------");
			Intent intent =  new Intent(this, ShopListActivity.class);
			intent.putExtra("type", string);
			this.startActivity(intent);
		}
		//根据学校查询所有发布信息
		if(v == btn_whole){
			school = "";
			onUpdate();
		}
		//根据学校查询本校的发布信息
		if(v == btn_my_school){
			Users users = (Users) myApplication.userMap.get("user");
			//判断是用户否登陆
			if (users != null) {
				school = users.getSchool();
				onUpdate();
			}else {
				//如果没有登录则弹出确认登陆对话框
//				tv_content.setVisibility(View.VISIBLE);
//				tv_content.setText("您好，您还没有登陆，请先登录!");
				dialog.setContentView(dialogView);
				dialog.show();
//				btn_back.setVisibility(View.VISIBLE);
//				btn_back.setOnClickListener(this); 
//				btn_determine.setVisibility(View.VISIBLE); 
//				btn_determine.setOnClickListener(this);
			}
		}
		//对话框的取消按钮
		if(v == btn_back){
			//关闭对话框
			dialog.dismiss();
		}
		if(v == btn_determine){
			//确定后跳到登录页面          
			dialog.dismiss();
			Intent intent = new Intent(this,LoginActivity.class);
			this.startActivity(intent);
		}
	}
	
	//初始化下拉刷新
	private void initPullDownView() {
		// 设置下拉刷新处理器
		list_pdv.setUpdateHandler(this);
		//点击查看物品详情
		lv_list.setOnItemClickListener(this);
		//初始化底部视图
		this.footer = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.listview_footer, null);
		listView_foot_progress = (ProgressBar) findViewById(R.id.listview_foot_progress);
		listView_foot_more = (TextView) findViewById(R.id.listview_foot_more);
		
		lv_list.addFooterView(footer); //添加底部视图必须在setAdapter前
		lv_list.setFooterDividersEnabled(false);
		
		////////////////////////////////////////////////////////////
		adapter = new DemandListAdapter(this);
		lv_list.setAdapter(adapter);
		//设置滚动侦听器
		lv_list.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				//数据为空
				if(listDatas.isEmpty()){
					return;
				}
				// 判断是否滚动到底部
				if(scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE 
						&& lastItem == adapter.getCount()){
					if (hasMore) {
						listView_foot_progress.setVisibility(View.VISIBLE);
						listView_foot_more.setText("加载中...");
						loadData(++pageNo);
					}
				}
			}
			
			@Override      //0.view  1.总项目数  2. 可见项目数  3. 第一个可见项
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				lastItem = firstVisibleItem + visibleItemCount - 1;
			}
		});	
	}
	//点击查看物品详情
	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

		if(position == lv_list.getCount()-1){
			System.out.println("-----demand---position-------"+position);
		}else{
			ItemList itemList = listDatas.get(position);
			Bundle data = new Bundle();
			data.putSerializable("shopinfo", itemList);
			Intent intent = new Intent(this, DemandInfoActivity.class);
			intent.putExtras(data);
			this.startActivity(intent);
		}
	}	
	// 回调方法
	public void onUpdate() {
		pageNo = 1;
		lv_list.setSelection(0);
		loadData(pageNo);
	}

	//加载数据
	public void loadData(int pn) {
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("pageNo", pn);
		params.put("school", school);
		params.put("value", string);
		params.put("condition", condition);
		//listView底部设置
		if(pageNo == 1){
			listDatas.clear();
			//是否可见
			footer.setVisibility(View.GONE);
			//设置页脚分频器启用  <--需要底部分割线设置方法为：android:footerDividersEnabled="true"
			lv_list.setFooterDividersEnabled(false);
		}else {
			footer.setVisibility(View.VISIBLE);
			lv_list.setFooterDividersEnabled(true);
		}
		HttpHelper.asyncPost(Api.URL + "/second-hand/look_list.do", params, new Callback() {
			
			@Override
			public void dataLoaded(Message msg) {
				
				//不显示底部
				footer.setVisibility(View.GONE);
				if(HttpStatus.SC_OK != msg.what){
					AppException.http(msg.what).makeToast(DemandListActivity.this);
					list_pdv.endUpdate();
					return;
				}
				String json = (String) msg.obj;
				Log.v("---------demand----------", json);
				PageModel<ItemList> pm = PageModel.jsonConvert(json);
				listDatas.addAll(pm.getData());
				adapter.setItemList(listDatas);
				/**
				 * notifyDataSetChanged方法
				 * 通过一个外部的方法控制如果适配器的内容改变时需要强制调用getView来刷新每个Item的内容,
				 * 可以实现动态的刷新列表的功能。
				 * endUpdate方法
				 * 它们在操纵基础数据或控件属性时取消了控件的重新绘制。
				 * 通过使用BeginUpdate 和 EndUpdate 方法，您可以对控件进行重大更改，
				 * 并且避免在应用这些更改时让控件经常重新绘制自身。
				 * 此类重新绘制会导致性能显著降低，并且用户界面闪烁且不反应。
				 */
				adapter.notifyDataSetChanged();
				list_pdv.endUpdate();
				
				if (pageNo < pm.getPageCount()) {
					hasMore = true;
				}else {
					hasMore = false;
					System.out.println("-----------??????1-----------");
//					footer.setVisibility(View.VISIBLE); //可见
//					listView_foot_progress.setVisibility(View.INVISIBLE); //不可见
//					listview_foot_more.setText("已加载全部信息");
					System.out.println("-----------??????2-----------");
				}
			}
		});
	}
}
